package com.hailiao.devicebasicsdkdemo.fragment

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.clj.fastble.BleManager
import com.dlong.dialog.JustLoadDialog
import com.hailiao.devicebasicsdkdemo.R
import com.hailiao.devicebasicsdkdemo.databinding.FragmentSendBinding
import com.hailiao.hlblelib.HLBleManager
import com.hailiao.hlblelib.constant.BleConstant
import com.hailiao.hlblelib.utils.hexToByteArray
import com.hailiao.hlblelib.utils.idEncrypt1
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 发送指令页面
 *
 * @Author: D10NG
 * @Time: 2020/12/16 7:36 下午
 */
class SendFragment : BaseFragment() {

    private lateinit var binding: FragmentSendBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_send, container, false)
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // 监听接收到的消息
        HLBleManager.instance(act.application).messageWorker.receiveMessageLive.observe(this.viewLifecycleOwner, {
            it?.let { info ->
                val content = info.content.hexToByteArray().toString(BleConstant.GBK_CHARSET)
                binding.txtReceive = "${binding.txtReceive}\n收到：$content"
            }
        })
        
        // 监听设备是否连接着
        act.connectedBleDeviceLive.observe(this.viewLifecycleOwner, {
            if (it == null) navController.navigateUp()
        })

        // 监听目标卡号和等待时间
        act.deviceSendMessageInfoLive.observe(this.viewLifecycleOwner, {
            binding.txtCard = it?.cardNumber?: ""
            binding.txtWait = (it?.waitTimeSecond?: 0).toString()
        })

        // 监听自检信息
        act.deviceCheckSelfInfoLive.observe(this.viewLifecycleOwner, {
            it?.let {  info ->
                // 初始化卡号，默认为自己的卡号，测试自发自收
                if (binding.edtText1.text?.toString() == "00000000") {
                    binding.edtText1.setText(info.idNumber)
                }
                // 显示信号状态
                binding.txtBdSignal = info.bdSignalType.strValue
            }
        })

        // 返回
        binding.toolbar.setNavigationOnClickListener {
            // 断开蓝牙连接
            BleManager.getInstance().disconnectAllDevice()
            navController.navigateUp()
        }

        // 设置textview可滚动
        binding.textView.movementMethod = ScrollingMovementMethod.getInstance()
        binding.textView2.movementMethod = ScrollingMovementMethod.getInstance()

        // 点击设置卡号
        binding.btnSetCard.setOnClickListener {
            // 检验卡号
            val cardId = binding.edtText1.text?.toString()?: ""
            if (cardId.isEmpty()) {
                act.showSnackBar("中心卡号不能为空！")
                return@setOnClickListener
            }
            val bleManager = HLBleManager.instance(act.application)
            // 显示弹窗
            val dialog = JustLoadDialog(act).create().show()
            GlobalScope.launch {
                // 设置卡号，需要使用加密idEncrypt1
                val result = bleManager.deviceSetWorker.setDeviceIds(idEncrypt1("", cardId))
                withContext(Dispatchers.Main) {
                    // 执行完成
                    binding.txtResult = result?.toReadString()?: "设置失败！"
                    dialog.dismiss()
                    // 将等待时间设置成-1，使得MainActivity里的checkWaitTimeJob去检查一次中心卡号
                    val info = act.deviceSendMessageInfoLive.value!!
                    info.waitTimeSecond = -1
                    act.deviceSendMessageInfoLive.postValue(info)
                }
            }
        }

        // 点击发送下消息
        binding.btnSend.setOnClickListener {
            // 检验发送内容
            val content = binding.edtText2.text?.toString()?: ""
            if (content.isEmpty()) {
                act.showSnackBar("发送内容不能为空！")
                return@setOnClickListener
            }
            val bleManager = HLBleManager.instance(act.application)
            // 显示弹窗
            val dialog = JustLoadDialog(act).create().show()
            GlobalScope.launch {
                // 发送消息
                val result = bleManager.basicWorker.sendBasicMessage(binding.txtCard!!, content)
                withContext(Dispatchers.Main) {
                    // 发送完成
                    binding.txtResult = result?.toReadString()?: "发送超时"
                    dialog.dismiss()
                    // 将等待时间设置成60，使得MainActivity里的checkWaitTimeJob去检查一次等待时间
                    val info = act.deviceSendMessageInfoLive.value!!
                    info.waitTimeSecond = 60
                    act.deviceSendMessageInfoLive.postValue(info)
                }
            }
        }
    }
}